import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  X,
  Lightbulb,
  CheckCircle,
  MapPin,
  Settings,
  AlertTriangle,
  TrendingUp,
} from "lucide-react";

const crossingTypeMap = {
  powerLineOutagePlus500: "跨越电力线路（带电）",
  powerLineOutagePlus110: "  跨越电力线路（不带电）",
  railway: "跨越普通铁路",
  railwayHighSpeed: "跨越高铁",
  firstHighway: "跨越高速公路(含全封闭一级公路)",
  highwayGradePlus2: "跨越公路(二级及以下公路)",
  navigableRivers: "跨越通航河流",
  noNavigableRivers: "跨越不通航河流",
  railwayNormal: "跨越通信线路",
  other: "其它",
};

export default function SchemeRecommendation({
  crossingPoints,
  projects,
  onAccept,
  onCancel,
  preSelectedCrossingPoint,
}) {
  const [selectedPointId, setSelectedPointId] = useState("");
  const [recommendation, setRecommendation] = useState(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);

  // 当有预选跨越点时，自动开始分析
  useEffect(() => {
    if (preSelectedCrossingPoint) {
      setSelectedPointId(preSelectedCrossingPoint.id);
      // 自动开始分析
      analyzeAndRecommend(preSelectedCrossingPoint);
    }
  }, [preSelectedCrossingPoint]);

  const analyzeAndRecommend = (selectedPoint = null) => {
    const point =
      selectedPoint || crossingPoints.find((p) => p.id === selectedPointId);
    if (!point) return;

    setIsAnalyzing(true);

    // 模拟AI分析延迟
    setTimeout(() => {
      const recommendations = getRecommendations(point);
      setRecommendation({
        crossingPoint: point,
        recommendations: recommendations,
        bestMethod: recommendations[0],
      });
      setIsAnalyzing(false);
    }, 2000);
  };

  const getRecommendations = (point) => {
    const methods = [];

    // 基于跨越类型和参数推荐方法
    switch (point.crossingType) {
      case "highwayExpressway":
      case "railwayHighSpeed":
        methods.push({
          method: "helicopterStringing",
          score: 95,
          reasoning: "高速公路/高铁跨越，安全与效率要求极高，直升机施工最适宜",
          advantages: ["施工速度快", "对交通影响最小", "安全性高"],
          disadvantages: ["成本较高", "天气要求严格", "空域申请复杂"],
          estimatedCost: 30,
          estimatedDuration: 1, // Changed from 8 hours to 1 day
        });
        methods.push({
          method: "droneStringing",
          score: 80,
          reasoning: "无人机牵引技术成熟，成本适中，对交通影响小",
          advantages: ["成本适中", "操作灵活", "对交通影响小"],
          disadvantages: ["受风力影响大", "载重有限", "单次作业距离有限"],
          estimatedCost: 18,
          estimatedDuration: 2, // Changed from 12 hours to 2 days
        });
        break;

      case "railwayNormal":
      case "highwayGradePlus2":
        methods.push({
          method: "rocketStringing",
          score: 88,
          reasoning:
            "普通铁路/公路跨越，火箭炮牵引可在短时窗口内完成，性价比高",
          advantages: ["速度极快", "技术成熟", "精度高"],
          disadvantages: ["需要停运/封路配合", "设备较昂贵"],
          estimatedCost: 20,
          estimatedDuration: 1, // Changed from 4 hours to 1 day
        });
        methods.push({
          method: "mobileCrane",
          score: 85,
          reasoning: "档距较小或封路时间充裕时，汽车吊施工经济实用",
          advantages: ["成本低", "设备普及", "施工稳定"],
          disadvantages: ["需要交通管制", "施工周期长"],
          estimatedCost: 8,
          estimatedDuration: 2, // Changed from 16 hours to 2 days
        });
        break;

      case "riverNavigable":
        if (point.spanLength > 300) {
          methods.push({
            method: "helicopterStringing",
            score: 95,
            reasoning: "大跨度通航河流，直升机是最佳选择",
            advantages: ["适应大跨度", "不受水位影响", "施工灵活"],
            disadvantages: ["成本高", "天气敏感", "需停航配合"],
            estimatedCost: 40,
            estimatedDuration: 2, // Changed from 10 hours to 2 days
          });
        }
        methods.push({
          method: "cablePulling",
          score: 80,
          reasoning: "中等跨度河流，地面牵引法经济适用",
          advantages: ["成本适中", "技术成熟", "可靠性高"],
          disadvantages: ["受季节影响", "需要船舶配合"],
          estimatedCost: 12,
          estimatedDuration: 3, // Changed from 20 hours to 3 days
        });
        break;

      case "power_line_outage_500kv_plus":
      case "power_line_live_110kv_plus":
      case "powerLineOutagePlus10":
        methods.push({
          method: "scaffoldingErection",
          score: 92,
          reasoning: "跨越重要带电线路，搭设跨越架是最可靠的硬隔离方式",
          advantages: ["安全性最高", "隔离效果好", "适用性强"],
          disadvantages: ["成本高", "施工周期长", "占用场地"],
          estimatedCost: 22,
          estimatedDuration: 6, // Changed from 48 hours to 6 days
        });
        methods.push({
          method: "manualStringing",
          score: 82,
          reasoning: "对于低压或停电线路，人工展放配合绝缘工具是经济方案",
          advantages: ["成本低", "灵活性高", "无需大型设备"],
          disadvantages: ["劳动强度大", "安全风险高", "效率低"],
          estimatedCost: 5,
          estimatedDuration: 3, // Changed from 24 hours to 3 days
        });
        break;

      default:
        methods.push({
          method: "scaffoldingErection",
          score: 75,
          reasoning: "其他常规跨越，搭设跨越架较为经济",
          advantages: ["成本低", "技术成熟", "施工稳定"],
          disadvantages: ["施工周期长", "占用场地"],
          estimatedCost: 10,
          estimatedDuration: 2, // Changed from 14 hours to 2 days
        });
    }

    // 根据难度和优先级调整推荐
    if (point.difficultyLevel === "critical" || point.priority === "urgent") {
      methods.forEach((m) => {
        if (m.method === "helicopterStringing") m.score += 10;
      });
    }

    return methods.sort((a, b) => b.score - a.score);
  };

  const getMethodLabel = (method) => {
    const labels = {
      helicopterStringing: "直升机展放",
      droneStringing: "无人机牵引",
      rocketStringing: "火箭炮牵引",
      cablePulling: "地面牵引",
      towerCrane: "塔式起重机",
      mobileCrane: "汽车起重机",
      manualStringing: "人工架线",
      scaffoldingErection: "搭设跨越架",
      vehicleStringing: "车辆牵引",
    };
    return labels[method] || method;
  };

  const handleAcceptRecommendation = (selectedMethod) => {
    const scheme = {
      name: `${recommendation.crossingPoint.name}施工方案`,
      constructionMethod: selectedMethod.method,
      recommended_method: selectedMethod.method,
      methodReasoning: selectedMethod.reasoning,
      // costEstimation: selectedMethod.estimatedCost,
      totalDuration: selectedMethod.estimatedDuration, // This will now be in days
      weatherRequirements:
        selectedMethod.method === "helicopterStringing"
          ? "风力不超过6级，无降雨"
          : "正常天气条件",
      riskAssessment: selectedMethod.disadvantages.join("；"),
    };

    onAccept({
      crossingPoint: recommendation.crossingPoint,
      scheme: scheme,
    });
  };

  return (
    <Card className="mb-6 shadow-lg border-0">
      <CardHeader className="bg-gradient-to-r from-yellow-50 to-orange-50 border-b">
        <CardTitle className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Lightbulb className="w-5 h-5 text-orange-600" />
            <span>智能施工方案推荐</span>
          </div>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>

      <CardContent className="p-6">
        {!recommendation ? (
          <div className="space-y-4">
            {/* 如果没有预选跨越点，显示选择界面 */}
            {!preSelectedCrossingPoint && (
              <>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    选择需要分析的跨越点
                  </label>
                  <Select
                    value={selectedPointId}
                    onValueChange={setSelectedPointId}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="请选择跨越点" />
                    </SelectTrigger>
                    <SelectContent>
                      {crossingPoints.map((point) => (
                        <SelectItem key={point.id} value={point.id}>
                          <div className="flex items-center gap-2">
                            <MapPin className="w-4 h-4" />
                            <span>
                              {point.name} - {point.crossingObject}
                            </span>
                            <Badge variant="outline" className="text-xs">
                              {crossingTypeMap[point.crossingType] ||
                                point.crossingType}
                            </Badge>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <Button
                  onClick={() => analyzeAndRecommend()}
                  disabled={!selectedPointId || isAnalyzing}
                  className="w-full bg-orange-600 hover:bg-orange-700"
                >
                  {isAnalyzing ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                      AI分析中...
                    </>
                  ) : (
                    <>
                      <Lightbulb className="w-4 h-4 mr-2" />
                      开始智能分析
                    </>
                  )}
                </Button>
              </>
            )}

            {/* 如果有预选跨越点，显示分析状态 */}
            {preSelectedCrossingPoint && (
              <div className="text-center space-y-4">
                <div className="bg-blue-50 p-4 rounded-lg">
                  <h3 className="font-semibold text-blue-900 mb-2 flex items-center gap-2 justify-center">
                    <MapPin className="w-4 h-4" />
                    正在分析: {preSelectedCrossingPoint.name}
                  </h3>
                  <p className="text-sm text-blue-700">
                    跨越对象: {preSelectedCrossingPoint.crossingObject} | 类型:{" "}
                    {preSelectedCrossingPoint.crossingType} | 档距:{" "}
                    {preSelectedCrossingPoint.spanLength}m
                  </p>
                </div>

                <div className="flex items-center justify-center gap-2 text-orange-600">
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-orange-600"></div>
                  <span className="font-medium">AI正在分析最佳施工方案...</span>
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="space-y-6">
            {/* Selected Crossing Point Info */}
            <div className="bg-blue-50 p-4 rounded-lg">
              <h3 className="font-semibold text-blue-900 mb-2 flex items-center gap-2">
                <MapPin className="w-4 h-4" />
                {recommendation.crossingPoint.name}
              </h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                <div>
                  <span className="text-blue-600">类型:</span>
                  <span className="ml-1">
                    {crossingTypeMap[
                      recommendation.crossingPoint.crossingType
                    ] || recommendation.crossingPoint.crossingType}
                  </span>
                </div>
                <div>
                  <span className="text-blue-600">档距:</span>
                  <span className="ml-1">
                    {recommendation.crossingPoint.spanLength}m
                  </span>
                </div>
                <div>
                  <span className="text-blue-600">难度:</span>
                  <span className="ml-1">
                    {recommendation.crossingPoint.difficultyLevel}
                  </span>
                </div>
                <div>
                  <span className="text-blue-600">优先级:</span>
                  <span className="ml-1">
                    {recommendation.crossingPoint.priority}
                  </span>
                </div>
              </div>
            </div>

            {/* Recommendations */}
            <div>
              <h3 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-green-600" />
                推荐方案 (按匹配度排序)
              </h3>

              <div className="space-y-4">
                {recommendation.recommendations.map((method, index) => (
                  <Card
                    key={method.method}
                    className={`border-2 transition-all duration-200 ${
                      index === 0
                        ? "border-green-200 bg-green-50"
                        : "border-gray-200 hover:border-blue-200"
                    }`}
                  >
                    <CardContent className="p-4">
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center gap-3">
                          <div
                            className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                              index === 0 ? "bg-green-100" : "bg-gray-100"
                            }`}
                          >
                            <Settings
                              className={`w-5 h-5 ${
                                index === 0 ? "text-green-600" : "text-gray-600"
                              }`}
                            />
                          </div>
                          <div>
                            <h4 className="font-semibold text-gray-900">
                              {getMethodLabel(method.method)}
                            </h4>
                            <div className="flex items-center gap-2">
                              <span className="text-sm text-green-600 font-medium">
                                匹配度: {method.score}%
                              </span>
                              {index === 0 && (
                                <Badge className="bg-green-100 text-green-700 border-green-200">
                                  推荐
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>

                        <div className="text-right text-sm text-gray-600">
                          <div>成本: {method.estimatedCost}万元</div>
                          <div>工期: {method.estimatedDuration}天</div>{" "}
                        </div>
                      </div>

                      <p className="text-sm text-gray-700 mb-3">
                        <span className="font-medium">选择理由: </span>
                        {method.reasoning}
                      </p>

                      <div className="grid md:grid-cols-2 gap-3 mb-3">
                        <div>
                          <h5 className="text-xs font-medium text-green-700 mb-1">
                            优势
                          </h5>
                          <ul className="text-xs text-gray-600 space-y-1">
                            {method.advantages.map((adv, i) => (
                              <li key={i} className="flex items-center gap-1">
                                <CheckCircle className="w-3 h-3 text-green-500" />
                                {adv}
                              </li>
                            ))}
                          </ul>
                        </div>

                        <div>
                          <h5 className="text-xs font-medium text-orange-700 mb-1">
                            注意事项
                          </h5>
                          <ul className="text-xs text-gray-600 space-y-1">
                            {method.disadvantages.map((dis, i) => (
                              <li key={i} className="flex items-center gap-1">
                                <AlertTriangle className="w-3 h-3 text-orange-500" />
                                {dis}
                              </li>
                            ))}
                          </ul>
                        </div>
                      </div>

                      <Button
                        onClick={() => handleAcceptRecommendation(method)}
                        variant={index === 0 ? "default" : "outline"}
                        size="sm"
                        className={
                          index === 0 ? "bg-green-600 hover:bg-green-700" : ""
                        }
                      >
                        采用此方案
                      </Button>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
